package com.zjc.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjc.common.R;
import com.zjc.pojo.StuRoom;
import com.zjc.pojo.Student;
import com.zjc.service.BuliderService;
import com.zjc.service.StuRoomService;
import com.zjc.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 周佳成
 * @since 2023-09-17
 */
@RestController
@RequestMapping("/api/sturoom")
public class StuRoomController {
	@Autowired
	StuRoomService stuRoomService;
   	@Autowired
   	StudentService studentService;
	@Autowired
	BuliderService buliderService;
	@GetMapping("/find")
	public R<Page> GetSturoomPage(int pageNum, int pageSize, Integer search){
		QueryWrapper<StuRoom> wrapper = new QueryWrapper<>();
		if(search!=null){
			wrapper.eq("room_id",search);
		}

		wrapper.orderByAsc("room_id");
		Page<StuRoom> page1 = new Page<>(pageNum,pageSize);
		stuRoomService.page(page1,wrapper);
		return R.success(page1);
	}
	@PutMapping("/update")
	public R<String> changeRoom(@RequestBody StuRoom sturoom){
		Integer ldid = sturoom.getLdId();

		if(!buliderService.isExistBulider(ldid)){
			return R.error("楼栋号不存在！");
		}
		boolean rows=stuRoomService.updateById(sturoom);
		if(rows){
			return R.success("修改成功");
		}
		else{
			return R.error("修改失败");
		}

	}
	@PostMapping("/add")
	public R<String> addRoom(@RequestBody StuRoom sturoom){
		Integer roomid = sturoom.getRoomId();
		Integer ldid = sturoom.getLdId();
		if(studentService.isRoomExists(roomid)){
			return R.error("房间号已经存在！");
		}
		if(!buliderService.isExistBulider(ldid)) {
			return R.error("楼栋不存在！！");
		}
		stuRoomService.save(sturoom);
		return R.success("添加成功");
	}

	@DeleteMapping("/delete/{roomId}")
	public R<String> deleteRoom(@PathVariable Integer roomId){
		System.out.println(roomId);
		int rows=stuRoomService.deleteRoom(roomId);
		StuRoom stuRoom = stuRoomService.getById(roomId);
		if(stuRoom.getRoomRealpeople()!=0){
			return R.error("房间仍有住，不可删除该房间信息！！！");
		}
		if(rows!=0){
			return R.success("删除成功");
		}
		else{
			return R.error("删除失败");
		}
	}
	//获取空宿舍数
	@GetMapping("/getEemptyRoom")
	public R<Long> getEemptyRoom(){
		LambdaQueryWrapper<StuRoom> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(StuRoom::getRoomRealpeople,0);
		Long num = stuRoomService.count(lambdaQueryWrapper);
		return R.success(num);
	}
	@GetMapping("/info")
	public R<StuRoom> getSturoombyId(int ldId,int roomId){
		LambdaQueryWrapper<StuRoom> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(StuRoom::getLdId,ldId).eq(StuRoom::getRoomId,roomId);
		StuRoom stuRoom = stuRoomService.getOne(lambdaQueryWrapper);
		return R.success(stuRoom);
	}

}

